package com.prolestar.publicsentiment.service.impl;


import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.enums.CellExtraTypeEnum;
import com.alibaba.fastjson2.JSONObject;
import com.prolestar.Enum.*;
import com.prolestar.common.core.domain.AjaxResult;
import com.prolestar.common.core.domain.model.LoginUser;
import com.prolestar.common.utils.DateUtils;
import com.prolestar.common.utils.ServletUtils;
import com.prolestar.publicsentiment.domain.*;
import com.prolestar.publicsentiment.mapper.PsPublicsentimentMapper;
import com.prolestar.publicsentiment.service.IPsPublicsentimentService;
import com.prolestar.service.TokenServices;
import com.prolestar.system.service.ISysDeptService;
import com.prolestar.system.service.ISysRoleService;
import com.prolestar.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 舆情处置Service业务层处理
 *
 * @author ruoyi
 * @date 2022-11-11
 */
@Service
public class PsPublicsentimentServiceImpl implements IPsPublicsentimentService {
    @Autowired
    private PsPublicsentimentMapper psPublicsentimentMapper;

    @Autowired
    private TokenServices tokenServices;

    @Autowired
    private ISysRoleService sysRoleService;

    @Autowired
    private ISysDeptService sysDeptService;

    @Autowired
    private ISysUserService sysUserService;


    /**
     * 查询舆情处置
     *
     * @param id 舆情处置主键
     * @return 舆情处置
     */
    @Override
    public PsPublicsentiment selectPsPublicsentimentById(Long id) {
        LoginUser loginUser = tokenServices.getLoginUser(ServletUtils.getRequest());
        Set<String> permission = sysRoleService.selectRolePermissionByUserId(loginUser.getUserId());
        PsPublicsentiment psPublicsentiment = null;
        if (permission.contains("admin") || permission.contains("conservator")) {
            psPublicsentiment = psPublicsentimentMapper.selectPsPublicsentimentById(id);
        }
        return psPublicsentiment;
    }

    /**
     * 查询舆情详情
     *
     * @param psPublicsentiment
     * @return
     */
    @Override
    public PsPublicsentiment selectPSById(PsPublicsentiment psPublicsentiment) {
        LoginUser loginUser = tokenServices.getLoginUser(ServletUtils.getRequest());
        Set<String> permission = sysRoleService.selectRolePermissionByUserId(loginUser.getUserId());
        if (permission.contains("admin") || permission.contains("conservator")) {
            return psPublicsentimentMapper.selectPsPublicsentimentById(psPublicsentiment.getId());
        } else {
            return psPublicsentimentMapper.selectPsPublicsentimentUserById(psPublicsentiment.getTaskId());
        }
    }

    @Override
    public AjaxResult toLead(MultipartFile file, boolean updateSupport) throws IOException {
        EasyExcel.read(file.getInputStream(),PsPublicsentimentExc.class,new CommonEasyExcelListener(psPublicsentimentMapper))
                .extraRead(CellExtraTypeEnum.COMMENT) // 需要读取批注 默认不读取
                .extraRead(CellExtraTypeEnum.HYPERLINK)// 需要读取超链接 默认不读取
                .extraRead(CellExtraTypeEnum.MERGE)// 需要读取合并单元格信息 默认不读取
                .sheet()//指定读取哪个sheet
                .headRowNumber(1)//指定标题行(需要)
                .doRead();//执行读取
        return AjaxResult.success();
    }





    /**
     * 查询舆情处置列表
     *
     * @param psPublicsentiment 舆情处置
     * @return 舆情处置
     */
    @Override
    public List<PsPublicsentiment> selectPsPublicsentimentList(PsPublicsentiment psPublicsentiment) {
        LoginUser loginUser = tokenServices.getLoginUser(ServletUtils.getRequest());
        Long userId = loginUser.getUserId();
        Long deptId = loginUser.getDeptId();
        psPublicsentiment.setDeptId(deptId);
        Set<String> permission = sysRoleService.selectRolePermissionByUserId(userId);
        if (permission.contains("admin") || permission.contains("conservator")) {
            return psPublicsentimentMapper.selectPsPublicsentimentList(psPublicsentiment);
        } else {
            return psPublicsentimentMapper.selectPsPublicsentimentUserList(psPublicsentiment);
        }

    }

    /**
     * 新增舆情处置
     *
     * @param psPublicsentiment 舆情处置
     * @return 结果
     */
    @Override
    public int insertPsPublicsentiment(PsPublicsentiment psPublicsentiment) {
        PsDealLog psDealLog = new PsDealLog();
        LoginUser loginUser = tokenServices.getLoginUser(ServletUtils.getRequest());
        Long userId = loginUser.getUserId();
        psPublicsentiment.setCreateBy(userId.toString());
        psPublicsentiment.setCreateTime(DateUtils.getNowDate());
        psPublicsentiment.setIsDelete(PublicsentimentDeleteStatus.NODELETS);
        psPublicsentiment.setPsStatus(PublicsentimentStatus.SUBMIT);
        psPublicsentiment.setIsAttention(PublicsentimentAttentionStatus.NOSPECIALFOCUS);
        int psId = psPublicsentimentMapper.insertPsPublicsentiment(psPublicsentiment);
        psPublicsentiment.setCreateTime(DateUtils.getNowDate());
        psDealLog.setDealType("新增");
        psDealLog.setDealBy(userId);
        psDealLog.setDealTime(DateUtils.getNowDate());
        psDealLog.setPsId(psPublicsentiment.getId());
        psPublicsentimentMapper.insertPsDealLog(psDealLog);
        return psId;

    }

    /**
     * 修改舆情处置
     *
     * @param psPublicsentiment 舆情处置
     * @return 结果
     */
    @Override
    public int updatePsPublicsentiment(PsPublicsentiment psPublicsentiment) {
        LoginUser loginUser = tokenServices.getLoginUser(ServletUtils.getRequest());
        Long userId = loginUser.getUserId();
        psPublicsentiment.setUpdateTime(DateUtils.getNowDate());
        PsDealLog psDealLog = new PsDealLog();
        psDealLog.setPsId(psPublicsentiment.getId());
        psDealLog.setDealType("修改");
        psDealLog.setDealBy(userId);
        psDealLog.setDealTime(DateUtils.getNowDate());
        psPublicsentimentMapper.insertPsDealLog(psDealLog);
        return psPublicsentimentMapper.updatePsPublicsentiment(psPublicsentiment);
    }

    /**
     * 批量删除舆情处置
     *
     * @param ids 需要删除的舆情处置主键
     * @return 结果
     */
    @Override
    public AjaxResult deletePsPublicsentimentByIds(Long[] ids) {
        for (Long id : ids) {
            psPublicsentimentMapper.updatePsStatusById(id);
        }
        return AjaxResult.success();

    }

    /**
     * 删除舆情处置信息
     *
     * @param id 舆情处置主键
     * @return 结果
     */
    @Override
    public int deletePsPublicsentimentById(Long id) {
        return psPublicsentimentMapper.deletePsPublicsentimentById(id);
    }



    /**
     * 舆情处置分派处理
     *
     * @param apportionPubilcsentiment
     * @return
     */
    @Override
    public AjaxResult apportion(ApportionPubilcsentiment apportionPubilcsentiment) {
        ApportionPubilcsentiment pubilcsentiment = new ApportionPubilcsentiment();
        PsPublicsentiment psPublicsentiment = new PsPublicsentiment();
        LoginUser loginUser = tokenServices.getLoginUser(ServletUtils.getRequest());
        Long userId = loginUser.getUserId();
        Set<String> permission = sysRoleService.selectRolePermissionByUserId(userId);
        // 是管理员就把状态改为已分派
        if (permission.contains("admin") || permission.contains("conservator")) {
            psPublicsentiment.setPsStatus(PublicsentimentStatus.ASSIGNED);
            psPublicsentiment.setId(apportionPubilcsentiment.getPsId());
            psPublicsentimentMapper.updatePsPublicsentiment(psPublicsentiment);
        } else {
            pubilcsentiment.setStatus(ApportionStatus.WAITRECEIVINGMODE);  // 单位人员代接受
        }
        pubilcsentiment.setPsId(apportionPubilcsentiment.getItemId());
        pubilcsentiment.setDistriBy(userId);
        pubilcsentiment.setDistriTime(DateUtils.getNowDate());
        pubilcsentiment.setSign(SignStatus.NOSIGN);
        pubilcsentiment.setReadStatus(ReadStatus.NOREAD);
        List<Long> list = apportionPubilcsentiment.getIds();
        list.forEach(l -> {
            pubilcsentiment.setDistriUnitId(l.toString());
            psPublicsentimentMapper.addApportion(pubilcsentiment);
        });
        PsDealLog psDealLog = new PsDealLog();
        psDealLog.setPsId(apportionPubilcsentiment.getItemId());
        psDealLog.setDealType("分派");
        psDealLog.setDealBy(userId);
        psDealLog.setDealTime(DateUtils.getNowDate());
        List<String> collect = list.stream().map(ls -> sysDeptService.selectDeptById(ls).getDeptName()).collect(Collectors.toList());
        psDealLog.setDealContent(JSONObject.toJSONString(collect));
        psPublicsentimentMapper.insertPsDealLog(psDealLog); // 存入单位日志表
        return AjaxResult.success();
    }

    /**
     * 查询所有--首页数据
     */
    @Override
    public List<PsPublicsentiment> selectAll() {
        return psPublicsentimentMapper.selectAll();
    }

    /**
     * 、
     * 舆情处置 普通人员处理
     *
     * @param apportionPubilcsentiment
     * @return
     */
    @Override
    public AjaxResult dispose(ApportionPubilcsentiment apportionPubilcsentiment) {

        LoginUser loginUser = tokenServices.getLoginUser(ServletUtils.getRequest());
        Long userId = loginUser.getUserId();
        Long deptId = loginUser.getDeptId();
        Set<String> permission = sysRoleService.selectRolePermissionByUserId(userId);
        // 更新管理员界面---已处理
        PsPublicsentiment psPublicsentiment = new PsPublicsentiment();
        psPublicsentiment.setPsStatus(PublicsentimentStatus.CONFIGUREDPROCESSORS);
        psPublicsentiment.setId(apportionPubilcsentiment.getPsId());
        psPublicsentimentMapper.updatePsPublicsentiment(psPublicsentiment);
        apportionPubilcsentiment.setDistriUnitId(deptId.toString());
        apportionPubilcsentiment.setStatus(ApportionStatus.CONFIGUREDPROCESSORS);
        apportionPubilcsentiment.setDealBy(userId);
        apportionPubilcsentiment.setDealTime(DateUtils.getNowDate());
        psPublicsentimentMapper.updateApportion(apportionPubilcsentiment);
        return AjaxResult.success();
    }

    /**
     * 签收
     *
     * @param apportionPubilcsentiment
     * @return
     */
    @Override
    public AjaxResult sign(ApportionPubilcsentiment apportionPubilcsentiment) {
        LoginUser loginUser = tokenServices.getLoginUser(ServletUtils.getRequest());
        Long deptId = loginUser.getDeptId();
        apportionPubilcsentiment.setDistriUnitId(deptId.toString());
        apportionPubilcsentiment.setSign(SignStatus.YESSIGN);
        psPublicsentimentMapper.updateApportionSign(apportionPubilcsentiment);
        return AjaxResult.success();
    }

    /**
     * 已读
     *
     * @param apportionPubilcsentiment
     * @return
     */
    @Override
    public AjaxResult read(ApportionPubilcsentiment apportionPubilcsentiment) {
        LoginUser loginUser = tokenServices.getLoginUser(ServletUtils.getRequest());
        Long deptId = loginUser.getDeptId();
        apportionPubilcsentiment.setDistriUnitId(deptId.toString());
        apportionPubilcsentiment.setReadStatus(ReadStatus.YESREAD);
        psPublicsentimentMapper.updateApportionRead(apportionPubilcsentiment);
        return AjaxResult.success();
    }

    /**
     * 退回(取消分派) - 改状态
     *
     * @param apportionPubilcsentiment
     * @return
     */
    @Override
    public AjaxResult sendBack(ApportionPubilcsentiment apportionPubilcsentiment) {
        PsPublicsentiment psPublicsentiment = new PsPublicsentiment();
        apportionPubilcsentiment.setStatus(ApportionStatus.SENDBACK);
        psPublicsentiment.setPsStatus(PublicsentimentStatus.SENDBACK);
        psPublicsentiment.setId(apportionPubilcsentiment.getPsId());
        psPublicsentimentMapper.updateApportionsendBack(apportionPubilcsentiment);
        psPublicsentimentMapper.updatePsPublicsentiment(psPublicsentiment);
        return AjaxResult.success();
    }

    /**
     * 关注状态修改
     *
     * @param
     * @return
     */
    @Override
    public AjaxResult specialFocus(PsPublicsentiment psPublicsentiment) {
        if (psPublicsentiment.getIsAttention() == PublicsentimentAttentionStatus.NOSPECIALFOCUS) {
            psPublicsentiment.setIsAttention(PublicsentimentAttentionStatus.YESSPECIALFOCUS);
        } else {
            psPublicsentiment.setIsAttention(PublicsentimentAttentionStatus.NOSPECIALFOCUS);
        }
        psPublicsentimentMapper.updatePsStatus(psPublicsentiment);
        return AjaxResult.success();
    }

    /**
     * 涉及问题查找应对策略
     *
     * @param strategyByInvolved
     * @return
     */
    @Override
    public List<StrategyByInvolved> StrategyByInvolved(StrategyByInvolved strategyByInvolved) {
        return psPublicsentimentMapper.StrategyByInvolved(strategyByInvolved);
    }

    /**
     * 详情--处置情况
     *
     * @param apportionPubilcsentiment
     * @return
     */
    @Override
    public List<ApportionPubilcsentiment> taskList(ApportionPubilcsentiment apportionPubilcsentiment) {
        List<ApportionPubilcsentiment> taskList = psPublicsentimentMapper.taskList(apportionPubilcsentiment);
        ArrayList<ApportionPubilcsentiment> pubilcsentimentArrayList = new ArrayList<>();
        taskList.forEach(task -> {
            ApportionPubilcsentiment apportion = new ApportionPubilcsentiment();
            String deptName = null;
            String nickName = null;
            if (task.getDistriUnitId() != null) {
                deptName = sysDeptService.selectDeptById(Long.parseLong(task.getDistriUnitId())).getDeptName();
            }
            if (task.getDealBy() != null) {
                nickName = sysUserService.selectUserById(task.getDealBy()).getNickName();
            }
            apportion.setDealByName(nickName);
            apportion.setStatus(task.getStatus());
            apportion.setUnitName(deptName);
            apportion.setDealContent(task.getDealContent());
            pubilcsentimentArrayList.add(apportion);
        });
        return pubilcsentimentArrayList;
    }

    /**
     * 操作记录
     *
     * @param psDealLog
     * @return
     */
    @Override
    public List<PsDealLog> selectOperation(PsDealLog psDealLog) {

        List<PsDealLog> psDealLogs = psPublicsentimentMapper.selectOperation(psDealLog);
        ArrayList<PsDealLog> dealLogs = new ArrayList<>();
        psDealLogs.forEach(ps -> {
            PsDealLog dealLog = new PsDealLog();
            String nickName = null;
            if (ps.getDealBy() != null) {
                nickName = sysUserService.selectUserById(ps.getDealBy()).getNickName();
            }
            dealLog.setDealByName(nickName);
            dealLog.setDealTime(ps.getDealTime());
            dealLog.setDealType(ps.getDealType());
            dealLog.setDealContent(ps.getDealContent());
            dealLogs.add(dealLog);
        });
        return dealLogs;
    }


}
